package com.xiaoma.config;

import lombok.AllArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.Backoff;

import javax.annotation.PostConstruct;

/**
 * @Author: xiaoma
 * @Date: 2021/7/9 15:22
 * @description:
 *     #开启发送端消息抵达Broker确认
 *     publisher-confirms: true
 *     #开启发送端消息抵达Queue确认
 *     publisher-returns: true
 *     #如果抵达Queue 优先回调returns
 *     template:
 *       mandatory: true
 *     # 接收端手动ack消息
 *     listener:
 *      simple:
 *         acknowledge-mode: manual
 */
//@Configuration
public class RabbitConf {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Bean
    public MessageConverter messageConverter(){
        return  new Jackson2JsonMessageConverter();
    }
    //定制化RabbitTemplate  发送端2个回调
    @PostConstruct //对象创建完成后执行该方法
    public void initRabbitTemplate(){
        //设置确认回调 到达Broker后触发
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *
             * @param correlationData 消息唯一ID
             * @param b 消息是否成功收到
             * @param s 失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                System.out.println(correlationData);
                System.out.println(b);
                System.out.println(s);
            }
        });
        //设置确认回调 没有到达Queue后触发
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 消息没有投递给指定队列触发
             * @param message 失败消息的详细信息
             * @param i 回复的状态码
             * @param s 回复的文本内容
             * @param s1 消息的目标交换机
             * @param s2 消息的目标路由键
             */
            @Override
            public void returnedMessage(Message message, int i, String s, String s1, String s2) {
                System.out.println(message);
                System.out.println(i);
                System.out.println(s);
                System.out.println(s1);
                System.out.println(s2);
            }
        });
    }
}
